package org.helgoboss.document_database_orient_impl

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx
import org.helgoboss.document_database._
import java.io.File
import org.helgoboss.scala_additions.Implicits._

class UseLocalOrientDatabase(databaseDir: File) extends UseDatabase {
    val dbUrl = "local:/" + databaseDir.path
    
    createDbIfNecessary
    
    private def createDbIfNecessary {
        val dbDelegate = new ODatabaseDocumentTx(dbUrl)
        if (!dbDelegate.exists) {
            dbDelegate.create
            dbDelegate.close
        }
    }
    
    
    def apply[T](f: (Database) => T): T = {
        val dbDelegate = new ODatabaseDocumentTx(dbUrl)
        
        dbDelegate.open("admin", "admin")
        val db = new OrientDatabase(dbDelegate)
        try {
            f(db)
        } finally {
            dbDelegate.close
        }
    }
}